package com.deyou.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deyou.AppManager;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.event.DebookRulesEvent;
import com.deyou.event.HouseFacilityEvent;
import com.deyou.event.HouseInfoEvent;
import com.deyou.model.HouseResourceAttrBean;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.album.Album;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class HouseDetailIntroActivity extends BaseActivity {

    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.progress_one)
    View progressOne;
    @BindView(R.id.progress_two)
    View progressTwo;
    @BindView(R.id.progress_three)
    View progressThree;
    @BindView(R.id.progress_four)
    View progressFour;
    @BindView(R.id.progress_five)
    View progressFive;
    @BindView(R.id.iv_default_house_photo)
    ImageView ivDefaultHousePhoto;
    @BindView(R.id.tv_house_photo_notify)
    TextView tvHousePhotoNotify;
    @BindView(R.id.house_photo_layout)
    LinearLayout housePhotoLayout;
    @BindView(R.id.house_desc_title)
    TextView houseDescTitle;
    @BindView(R.id.tv_house_desc)
    TextView tvHouseDesc;
    @BindView(R.id.iv_desc_step_status)
    ImageView ivDescStepStatus;
    @BindView(R.id.house_desc_layout)
    RelativeLayout houseDescLayout;
    @BindView(R.id.house_price_title)
    TextView housePriceTitle;
    @BindView(R.id.tv_house_price)
    EditText tvHousePrice;
    @BindView(R.id.iv_price_step_status)
    ImageView ivPriceStepStatus;
    @BindView(R.id.house_price_layout)
    RelativeLayout housePriceLayout;
    @BindView(R.id.house_addr_title)
    TextView houseAddrTitle;
    @BindView(R.id.tv_house_addr)
    TextView tvHouseAddr;
    @BindView(R.id.iv_addr_step_status)
    ImageView ivAddrStepStatus;
    @BindView(R.id.house_addr_layout)
    RelativeLayout houseAddrLayout;
    @BindView(R.id.house_rules_title)
    TextView houseRulesTitle;
    @BindView(R.id.tv_house_rules)
    TextView tvHouseRules;
    @BindView(R.id.iv_rules_step_status)
    ImageView ivRulesStepStatus;
    @BindView(R.id.house_rules_layout)
    RelativeLayout houseRulesLayout;
    @BindView(R.id.house_debook_rules_title)
    TextView houseDebookRulesTitle;
    @BindView(R.id.iv_debook_rules)
    ImageView ivDebookRules;
    @BindView(R.id.iv_house_photo)
    ImageView ivHousePhoto;
    @BindView(R.id.house_debook_rules_layout)
    RelativeLayout houseDebookRulesLayout;
    @BindView(R.id.house_facility_title)
    TextView houseFacilityTitle;
    @BindView(R.id.iv_facility)
    ImageView ivFacility;
    @BindView(R.id.house_facility_layout)
    RelativeLayout houseFacilityLayout;
    @BindView(R.id.btn_add_house)
    TextView btnAddHouse;
    @BindView(R.id.house_name_layout)
    RelativeLayout houseNameLayout;
    @BindView(R.id.tv_house_name)
    TextView tvHouseName;
    private ArrayList<String> mImageList;
    private int stepCount = 0;
    private HouseResourceAttrBean houseDetailAttr;
    private String uploadImgUrl;
    private String houseName, houseDesc, houseRules = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_detail_intro);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        houseDetailAttr = (HouseResourceAttrBean) getIntent().getExtras().getSerializable("roomAndBenAttr");
        initView();
    }

    @Override
    protected boolean translucentStatusBar() {
        return super.translucentStatusBar();
    }

    private void initView() {
        tvMidTitle.setText("填写房屋资料");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("预览");
        tvRight.setTextColor(getResources().getColor(R.color.color_FF832D));
    }

    @OnClick({R.id.iv_left_back, R.id.tv_right, R.id.iv_default_house_photo, R.id.house_desc_layout, R.id.house_price_layout, R.id.house_photo_layout,
            R.id.house_addr_layout, R.id.house_rules_layout, R.id.house_debook_rules_layout, R.id.house_facility_layout, R.id.btn_add_house,
            R.id.house_name_layout})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.tv_right:
                AndroidUtils.startNextActivity(HouseDetailIntroActivity.this, HouseResourceDetailActivity.class, null, false);
                break;
            case R.id.iv_default_house_photo:
            case R.id.house_photo_layout:
                callAlbum();
                break;
            case R.id.house_name_layout:
                bundle.putInt("showType", 1);
                AndroidUtils.startNextActivity(HouseDetailIntroActivity.this, CommonInputActivity.class, bundle, false);
                break;
            case R.id.house_desc_layout:
                bundle.putInt("showType", 2);
                AndroidUtils.startNextActivity(HouseDetailIntroActivity.this, CommonInputActivity.class, bundle, false);
                break;
//            case R.id.house_price_layout:
//                break;
//            case R.id.house_addr_layout:
//                break;
            case R.id.house_rules_layout:
                bundle.putInt("showType", 3);
                AndroidUtils.startNextActivity(HouseDetailIntroActivity.this, CommonInputActivity.class, bundle, false);
                break;
            case R.id.house_debook_rules_layout:
                AndroidUtils.startNextActivity(HouseDetailIntroActivity.this, DeBookRulesActivity.class, null, false);
                break;
            case R.id.house_facility_layout:
                AndroidUtils.startNextActivity(HouseDetailIntroActivity.this, HouseFacilityListActivity.class, null, false);
                break;
            case R.id.btn_add_house:
//                addHouseResource();
                if (TextUtils.isEmpty(mImageList.get(0))) {
                    showToast("请先选择房源图片");
                    return;
                }
                uploadHouseImg();
                break;
        }
    }

    private void callAlbum() {
        Album.albumRadio(this)
                .toolBarColor(getResources().getColor(R.color.color_FF832D)) // Toolbar 颜色，默认蓝色。
                .statusBarColor(getResources().getColor(R.color.color_FF832D)) // StatusBar 颜色，默认蓝色。
                .title("图库") // 配置title。
                .columnCount(3) // 相册展示列数，默认是2列。
                .camera(true) // 是否有拍照功能。
                .start(999);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 999) {
            if (resultCode == RESULT_OK) { // Successfully.
                mImageList = Album.parseResult(data);
                if (null != mImageList && mImageList.size() > 0) {
                    ivDefaultHousePhoto.setVisibility(View.GONE);
                    tvHousePhotoNotify.setVisibility(View.GONE);
                    ivHousePhoto.setVisibility(View.VISIBLE);
                    new GlideImageLoader().displayImage(this, mImageList.get(0), ivHousePhoto);
                    stepCount += 1;
                    refreshProgressBarUI();
                } else {
                    ivDefaultHousePhoto.setVisibility(View.VISIBLE);
                    tvHousePhotoNotify.setVisibility(View.VISIBLE);
                    ivHousePhoto.setVisibility(View.GONE);
                }
            } else if (resultCode == RESULT_CANCELED) { // User canceled.
                // 用户取消了操作。
            }
        }
    }

    /**
     * 更新顶部进度条
     */
    private void refreshProgressBarUI() {
        switch (stepCount) {
            case 1:
                progressOne.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressTwo.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressThree.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressFour.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressFive.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                break;
            case 2:
                progressOne.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressTwo.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressThree.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressFour.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressFive.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                break;
            case 3:
                progressOne.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressTwo.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressThree.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressFour.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressFive.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                break;
            case 4:
                progressOne.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressTwo.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressThree.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressFour.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressFive.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                break;
            case 5:
                progressOne.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressTwo.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressThree.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressFour.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressFive.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                break;
            default:
                progressOne.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
                progressTwo.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressThree.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressFour.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                progressFive.setBackgroundColor(getResources().getColor(R.color.color_E5E5E5));
                break;
        }
    }

    private void uploadHouseImg() {
        final Bundle b = new Bundle();
        final Message msg = new Message();

        Observable.create(new ObservableOnSubscribe<Progress>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
                OkGo.<String>post(Urls.uploadImg)//
                        .tag(this)//
//                        .params("file",new File(imageItems.get(0).path))
                        //.params("file2",new File("文件路径"))
                        //.params("file3",new File("文件路径"))
                        .params("file", new File(mImageList.get(0)))//
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                e.onComplete();
                                SimpleResponse resp = new Gson().fromJson(response.body(), SimpleResponse.class);
                                if (null != resp) {
                                    if (resp.code == 1) {
                                        uploadImgUrl = resp.data;
                                        b.putInt("code", 4);
                                    } else {
                                        b.putInt("code", 2);
                                    }
                                    msg.setData(b);
                                    handler.sendMessage(msg);
                                } else {
                                    b.putInt("code", 5);
                                    msg.setData(b);
                                    handler.sendMessage(msg);
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                e.onError(response.getException());
                                b.putInt("code", 5);
                                msg.setData(b);
                                handler.sendMessage(msg);
                            }

                            @Override
                            public void uploadProgress(Progress progress) {
                                e.onNext(progress);
                            }
                        });
            }
        })//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        showLoading("房源图片上传中...");
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Observer<Progress>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull Progress progress) {
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    private void addHouseResource() {
        final Bundle b = new Bundle();
        final Message msg = new Message();
        JSONObject object = new JSONObject();
        try {
            object.put("resourceName", houseName);
            object.put("resourceIntroduction", houseDesc);
            object.put("resourceCodes", houseRules);
            object.put("resourceUserId", SPUtils.getStringByKey(this, Constants.UserId));
            object.put("resourceRentaltype", houseDetailAttr.resourceRentaltype);
            object.put("resourceType", houseDetailAttr.resourceType);
            object.put("resourceRegion", houseDetailAttr.resourceRegion);
            object.put("resourceAddress", houseDetailAttr.resourceAddress);
            object.put("resourceLongitude", houseDetailAttr.resourceLongitude);
            object.put("resourceLatitude", houseDetailAttr.resourceLatitude);
            object.put("resourceMaximumNum", houseDetailAttr.resourceMaximumNum);
            object.put("resourceBedroomNum", houseDetailAttr.resourceBedroomNum);
            object.put("resourceBedNum", houseDetailAttr.resourceBedNum);
            object.put("resourceToiletNum", houseDetailAttr.resourceToiletNum);
            object.put("resourceCancelDays", houseDetailAttr.resourceCancelDays);
            object.put("resourceRefundPercentage", houseDetailAttr.resourceRefundPercentage);
            object.put("resourceCustomRefund", houseDetailAttr.resourceCustomRefund);
            object.put("resourceInfrastructure", houseDetailAttr.resourceInfrastructure);
            object.put("resourceAmenities", houseDetailAttr.resourceAmenities);
            object.put("resourceSpecialFacilities", houseDetailAttr.resourceSpecialFacilities);
            object.put("resourcePic", uploadImgUrl);
            object.put("resourceCheckintime", "14:00");
            object.put("resourceCheckouttime", "12:00");
            object.put("resourcePrice", tvHousePrice.getText().toString());
            String paramJson = object.toString();
            Logger.i(Logger.LOGTAG + "添加房源", paramJson);
            ServerApi.getString(Urls.addHouseResource, "", AESUtil.encrypt(paramJson))
                    .subscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading("添加房源中...");
                        }
                    }).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull String s) {
                            SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                            if (null != resp) {
                                if (resp.code == 1) {
                                    b.putInt("code", 1);
                                } else {
                                    b.putInt("code", 2);
                                }
                                msg.setData(b);
                                handler.sendMessage(msg);
                            } else {
                                b.putInt("code", 3);
                                msg.setData(b);
                                handler.sendMessage(msg);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            b.putInt("code", 3);
                            msg.setData(b);
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.getData().getInt("code");
            switch (code) {
                case 1:
                    showToast("房源添加成功");
                    AppManager.getAppManager().addActivity(HouseDetailIntroActivity.this);
                    AppManager.getAppManager().finishAllActivity(HouseResourceListActivity.class);
                    break;
                case 2:
                    String errMsg = msg.getData().getString("errMsg");
                    showToast(errMsg);
                    break;
                case 3:
                    showToast("房源添加失败");
                    break;
                case 4:
                    addHouseResource();
                    break;
                case 5:
                    showToast("房源图片上传失败,请重新上传!");
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEventMainThread(DebookRulesEvent event) {
        if (null == event)
            return;
        houseDetailAttr.resourceCancelDays = event.getDebookDay();
        houseDetailAttr.resourceRefundPercentage = event.getDebookMoney();
        houseDetailAttr.resourceCustomRefund = event.getCustomDebookRule();
    }

    @Subscribe
    public void onEventMainThread(HouseFacilityEvent event) {
        if (null == event)
            return;
        houseDetailAttr.resourceInfrastructure = event.baseFacility;
        houseDetailAttr.resourceAmenities = event.easyFacility;
        houseDetailAttr.resourceSpecialFacilities = event.specialFacility;
    }

    @Subscribe
    public void onEventMainThread(HouseInfoEvent event) {
        if (null == event)
            return;
        switch (event.infoType) {
            case 1:
                houseName = event.houseInfo;
                tvHouseName.setText(event.houseInfo);
                break;
            case 2:
                houseDesc = event.houseInfo;
                tvHouseDesc.setText(event.houseInfo);
                break;
            case 3:
                houseRules = event.houseInfo;
                tvHouseRules.setText(event.houseInfo);
                break;
        }
    }
}
